package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.CoverMapper;
import com.bwie.mapper.RecordMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.Cover;
import com.bwie.pojo.Record;
import com.bwie.pojo.User;
import com.bwie.service.UserFeignService;
import com.bwie.utils.R;
import com.bwie.vo.EchartsVo;
import com.bwie.vo.RepairsPageVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.RepairsMapper;
import com.bwie.pojo.Repairs;
import com.bwie.service.RepairsService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author: 秋晚
 * @Date:  2025/7/7 20:27
 * @Description: 
 **/

@Service
@Transactional(rollbackFor = Exception.class)
public class RepairsServiceImpl extends ServiceImpl<RepairsMapper, Repairs> implements RepairsService{


    @Autowired
    RepairsMapper repairsMapper;

    @Autowired
    CoverMapper coverMapper;

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Autowired
    RecordMapper recordMapper;


    @Autowired
    UserFeignService userFeignService;

    @Autowired
    HttpServletResponse response;
    @Override
    public R getXyData() {
        ArrayList<String> x = new ArrayList<>();
        ArrayList<Integer> y = new ArrayList<>();
        HashMap<String, Object> map = new HashMap<>();
        //自定义查询
        List<EchartsVo> echartsVoList=repairsMapper.getXyData();
        for (EchartsVo echartsVo : echartsVoList) {
           x.add(echartsVo.getXData());
           y.add(echartsVo.getYData());
        }
        map.put("x",x);
        map.put("y",y);
        //放进map容器
        return R.OK(map);
    }

    @Override
    public R getStatusXy() {
        //获取x轴数据
        ArrayList<String> x=repairsMapper.getYearList();
        //获取y轴数据
        ArrayList<Integer> y1=repairsMapper.getCount(1);
        ArrayList<Integer> y2=repairsMapper.getCount(2);
        ArrayList<Integer> y3=repairsMapper.getCount(3);
        ArrayList<Integer> y4=repairsMapper.getCount(4);
        ArrayList<Integer> y5=repairsMapper.getCount(5);

        //放进map返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("x",x);
        map.put("y1",y1);
        map.put("y2",y2);
        map.put("y3",y3);
        map.put("y4",y4);
        map.put("y5",y5);
        return R.OK(map);
    }

    @Override
    public R getAreaXy() {
        //查询xy轴数据
        ArrayList<String> x=repairsMapper.getAreaXList();
        ArrayList<String> y1=repairsMapper.getAreaYList(1);
        ArrayList<String> y2=repairsMapper.getAreaYList(2);
        ArrayList<String> y3=repairsMapper.getAreaYList(3);
        ArrayList<String> y4=repairsMapper.getAreaYList(4);
        ArrayList<String> y5=repairsMapper.getAreaYList(5);

        //放进map容器
        HashMap<String, Object> map = new HashMap<>();
        map.put("x",x);
        map.put("y1",y1);
        map.put("y2",y2);
        map.put("y3",y3);
        map.put("y4",y4);
        map.put("y5",y5);
        return R.OK(map);
    }

    @Override
    public R repairsPage(RepairsPageVo repairsPageVo) {
        //创建分页对象
        Page<Repairs> repairsPage = new Page<>(repairsPageVo.getPageNum(), repairsPageVo.getPageSize());
        //后端自定义语句 分页作为第一个参数传递
        Page<Repairs> page=repairsMapper.repairsPage(repairsPage,
                repairsPageVo.getRepairsCode(),
                repairsPageVo.getRepairsType(),
                repairsPageVo.getRepairsStatus(),
                repairsPageVo.getRepairsUser(),
                repairsPageVo.getRepairsArea());
        for (Repairs record : page.getRecords()) {
            List<Cover> covers = coverMapper.selectList(new LambdaQueryWrapper<Cover>().eq(Cover::getRepairsId, record.getId()));
            record.setCoverList(covers);
        }

        return R.OK(page);
    }

    @Override
    public R saveRepairs(Repairs repairs) {
        //随机生成订单号
        String code = RandomUtil.randomNumbers(12);
        repairs.setRepairsCode(code);
        repairs.setRepairsStatus(1);

        //进行保存
        repairsMapper.insert(repairs);
        //返回主键id添加封面
        for (String url : repairs.getUrls()) {
            Cover cover = new Cover(null, repairs.getId(), url);
            coverMapper.insert(cover);
        }

        //添加记录表
        Record record = new Record(null,repairs.getId(),repairs.getRepairsUser(),1,new Date(),null,null);
        recordMapper.insert(record);

        return R.OK();
    }

    @Override
    public R uploadFile(MultipartFile file) {

        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String path="http://192.168.80.192:8888/"+storePath.getFullPath();
            return R.OK(path);
        } catch (IOException e) {
            e.printStackTrace();
            return R.ERROR(500,"上传失败！");
        }
    }

    @Override
    public R editRepairs(Repairs repairs) {
        //判断单号是否存在
        Repairs one = repairsMapper.selectOne(new LambdaQueryWrapper<Repairs>().eq(Repairs::getRepairsCode, repairs.getRepairsCode()));
        if(ObjectUtils.isEmpty(one)){
            return R.ERROR(500,"单号不存在!");
        }

        //进行修改
        repairsMapper.updateById(repairs);

        //删除原有的图片路径
        coverMapper.delete(new LambdaQueryWrapper<Cover>().eq(Cover::getRepairsId,repairs.getId()));
        //删除成功重新赋值
        for (String url : repairs.getUrls()) {
            Cover cover = new Cover(null, repairs.getId(), url);
            coverMapper.insert(cover);
        }
        return R.OK();
    }

    @Override
    public R getRecordById(Long id) {
        List<Record> records = recordMapper.selectList(new LambdaQueryWrapper<Record>().eq(Record::getRepairsId, id));

        return R.OK(records);
    }

    @Override
    public R upRepairsStatus(Repairs repairs) {
        //判断是否是转单
        if (repairs.getRepairsStatus().equals(4)) {
            //判断单号是否存在
            Repairs one = repairsMapper.selectOne(new LambdaQueryWrapper<Repairs>().eq(Repairs::getRepairsCode, repairs.getRepairsCode()));
            if(ObjectUtils.isEmpty(one)){
                return R.ERROR(500,"单号不存在!");
            }
            //是转单  首先修改承修人和状态
            one.setRepairsStatus(4);
            one.setRepairsUserId(repairs.getRepairsUserId());
            //修改
            repairsMapper.updateById(one);
            R r = userFeignService.getUserById(repairs.getRepairsUserId());
            if(r.getData()!=null){
                String jsonString = JSON.toJSONString(r.getData());
                User user = JSON.parseObject(jsonString, User.class);
                //记录流程
                Record record = new Record();
                record.setRepairsId(one.getId());
                record.setRecordStatus(one.getRepairsStatus());
                record.setRepairsUser(one.getRepairsUser());
                record.setOrderUsername(user.getUsername());
                record.setCreateTime(new Date());
                record.setRecordRemarks(repairs.getRecordRemarks());
                recordMapper.insert(record);
                return R.OK();
            }else{
                return r;
            }

        } else {
            //判断单号是否存在
            Repairs one = repairsMapper.selectOne(new LambdaQueryWrapper<Repairs>().eq(Repairs::getRepairsCode, repairs.getRepairsCode()));
            if(ObjectUtils.isEmpty(one)){
                return R.ERROR(500,"单号不存在!");
            }

            //只修改状态和派单人
            one.setRepairsStatus(repairs.getRepairsStatus());
            one.setRepairsUserId(repairs.getRepairsUserId());
            //进行修改
            repairsMapper.updateById(one);

            if(ObjectUtils.isEmpty(repairs.getRepairsUserId())){
                Record record = new Record();
                record.setRepairsId(one.getId());
                record.setRecordStatus(one.getRepairsStatus());
                record.setRepairsUser(one.getUsername());
                record.setCreateTime(new Date());
                recordMapper.insert(record);
                return R.OK();
            }else{
                //远程调用
                R r = userFeignService.getUserById(repairs.getRepairsUserId());
                if(r.getData()!=null){
                    String jsonString = JSON.toJSONString(r.getData());
                    User user = JSON.parseObject(jsonString, User.class);
                    //记录
                    Record record = new Record();
                    record.setRepairsId(one.getId());
                    record.setRecordStatus(one.getRepairsStatus());
                    record.setRepairsUser(one.getRepairsUser());
                    record.setOrderUsername(user.getUsername());
                    record.setCreateTime(new Date());
                    recordMapper.insert(record);
                    return R.OK();
                }else{
                    return r;
                }
            }
        }
    }

    @Override
    public void exportExcel() {
        //创建导出对象
        ExcelUtil<Repairs> excelUtil = new ExcelUtil<>(Repairs.class);
        //查询数据
        List<Repairs> repairs = repairsMapper.selectList(null);
        excelUtil.exportExcel(response,repairs,"报修记录");

    }

    @Override
    public R importExcel(MultipartFile file) {

        try {
            //导入
            ExcelUtil<Repairs> excelUtil = new ExcelUtil<>(Repairs.class);
            //插入导入数据
            List<Repairs> list = excelUtil.importExcel(file.getInputStream());
            //遍历添加
            for (Repairs repairs : list) {
                repairsMapper.insert(repairs);
            }

            return R.OK("导入成功,共导入"+list.size()+"条数据");
        } catch (IOException e) {
           e.printStackTrace();
           return R.ERROR(500,"导入失败!");
        }

    }

    @Override
    public R getEcharts() {
        Integer personCount=repairsMapper.selectPersonCount();
        Double priceSum=repairsMapper.selectPriceSumCount();
        Integer roomCount=repairsMapper.selectRoomCount();
        List<String> x=repairsMapper.getXData();
        List<Integer> y1=repairsMapper.getYData(1);
        List<Integer> y2=repairsMapper.getYData(3);

        HashMap<String, Object> map = new HashMap<>();
        map.put("personCount",personCount);
        map.put("priceSum",priceSum);
        map.put("roomCount",roomCount);
        map.put("x",x);
        map.put("y1",y1);
        map.put("y2",y2);
        return R.OK(map);
    }

}



